//
//  WBNetWorkManager.swift
//  DLSwift微博
//
//  Created by 丁浪涛 on 2016/11/13.
//  Copyright © 2016年 丁浪涛. All rights reserved.
//

import UIKit
import AFNetworking //倒入库文件夹名字

//swift的枚举支持任意数据类型
enum WBHTTPMethod
{
    case  GET
    case  POST
}

class WBNetWorkManager: AFHTTPSessionManager {

    //单例
    //静态区 （常量） (懒加载本质上是个闭包)
    //在第一次访问时 执行闭包 并且将结果保存在shared 中
    static let shared :WBNetWorkManager = {
    //实例化对象
    let  instance  = WBNetWorkManager()
        
        //设置响应反序列化的数据类型
      instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return instance
    }()
    
 
    //懒加载
    lazy var  userAccount = WBUserAccount()
    
    //计算型属性
    var userLogon: Bool{
        return userAccount.access_token != nil
    }
    //用户id

    
    //专门负责请求token的网络请求方法
    func tokenRequest(method: WBHTTPMethod = .GET,URLString: String,parameters:[String:AnyObject]?,completion:@escaping (_ json: Any? ,_ isSuccess : Bool)->())
    {
        guard let token  = userAccount.access_token else {
            print("没有token 需要登录")
            NotificationCenter.default.post(name: Notification.Name(WBUserShouldLoginNotification), object: nil)
            completion(nil ,true )
            return
        }
        
        var parameters = parameters
        //判断参数字典是否存在
        if parameters == nil {
            parameters = [String : AnyObject]()
        }
        parameters!["access_token"] = token as AnyObject?
        //发起真正的网络请求
        request(method: method, URLString: URLString, parameters: parameters!, completion: completion)
        
    }
    
    //使用一个函数 封装AFN的GET／POST请求
    func  request(method: WBHTTPMethod = .GET,URLString: String,parameters:[String:AnyObject],completion:@escaping (_ json: Any? ,_ isSuccess : Bool)->())
    {
        let  success  = {(task: URLSessionDataTask,json: Any?)->()  in
            completion(json as Any?,true)
            print("加载成功")
        }
        let fail  = { (task: URLSessionDataTask?,error: Error)->() in
            
            //针对403  处理 token过期情况
            if(   (task?.response as? HTTPURLResponse)?.statusCode == 403)
            {
                print("token 过期了")
                // FIME 发送通知 提示用户再次登录  本方法不知道谁被调用 谁接收到通知 谁处理
                NotificationCenter.default.post(name: Notification.Name(WBUserShouldLoginNotification), object: "bad token")
                //发送通知 去登出
            }
            print("加载失败:失败原因 \(error)")
            completion(nil ,false)
        }
        
        if method == .GET {
            get(URLString, parameters: parameters, progress: nil, success: success, failure: fail)
        }
        else
        {
            post(URLString, parameters: parameters, progress: nil, success: success, failure: fail)
        }
    }
    
}
